package ru.minidoc.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import ru.minidoc.dao.UserDao;
import ru.minidoc.model.User;

@Controller
public class AuthController {
    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/auth.page", method = RequestMethod.POST)
    public String auth(@ModelAttribute("user") User user, BindingResult result,
            SessionStatus status, HttpServletRequest request) {
        if (user == null) {
            result.addError(new FieldError("user", "login",  "Incorrect Login"));
            return "login";
        }
        User loggedUser = userDao.login(user);
        if (loggedUser == null) {
            result.addError(new FieldError("user", "login",  "Incorrect Login"));
            return "login";
        }
        RequestContextHolder.currentRequestAttributes().setAttribute("user",
                loggedUser, RequestAttributes.SCOPE_SESSION);
        status.setComplete();
        return "redirect:/main.action";
    }

    @RequestMapping(value = "/auth.page", method = RequestMethod.GET)
    public String auth(@ModelAttribute("user") User user, ModelMap model) {
        model.addAttribute("user", user);
        return "login";
    }
}
